#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;


 // Definition for singly-linked list.
  struct ListNode {
      int val;
      ListNode *next;
      ListNode() : val(0), next(nullptr) {}
      ListNode(int x) : val(x), next(nullptr) {}
      ListNode(int x, ListNode *next) : val(x), next(next) {}
  };
 
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        ListNode* pre = new ListNode();
        pre->next = head;
        ListNode* curr = head;
        ListNode* leftNode;
        ListNode* rightNode;
        ListNode* preLeft;
        int i = 1;
        while(curr!=nullptr){
            if(i < left){
                pre = curr;
                curr = curr->next;
                
            }
            else if(i>=left&&i<=right){
                if(i==left){
                    preLeft = curr;
                    curr = curr->next;
                    preLeft->next =nullptr;
                }
                else if(i==right){
                    ListNode* temp = curr->next;
                    curr->next = preLeft;

                    pre->next->next = temp;
                    pre->next = curr;
                    break;
                    
                }
                else{
                    ListNode* temp = curr->next;
                    curr->next = preLeft;
                    preLeft = curr;
                    curr = temp;

                }
            }
            
            ++i;
        }
        return (left==1)? (pre->next):(head);
    }
};

int main(){
    Solution S;
    ListNode* head = new ListNode(1);
    head->next = new ListNode(2);
    head->next->next = new ListNode(3);
    head->next->next->next = new ListNode(4);
    head->next->next->next->next = new ListNode(5);
    S.reverseBetween(head,1,4);
    return 0;
}